import React from 'react'
import PropTypes from 'prop-types'
import {Form,Card,Input,Icon,Button} from 'antd'
import {checkBankNum,patterns,post} from '../../Util'
const FormItem = Form.Item
const itemLayout = {
  labelCol: {
    span:8
  },
  wrapperCol: {
    span:14
  },
}
let banKeys = 0
class BankForm extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      bankCards:[{k:0}],
      bankCardLoading:false,
      bankCardIndex:-1,
    }
  }

  componentWillMount(){
    this.props.setForm(this.props.form)
  }
  insertBankCardName(index){
    let {bankCards} = this.props.form.getFieldsValue()
    console.log('getFormData:',bankCards)
    const num = bankCards[index].bankCardNumber
    if(!checkBankNum(num)){
      const _bankCards = this.state.bankCards
      this.setState({
        bankCards:bankCards.map((value,_index)=>{
          if(_index === index)
            value.bankName = undefined
          value.k = _bankCards[_index].k
          return value
        })
      })
      return
    }
    this.setState({
      bankCardLoading:true,
      bankCardIndex:index,
    })
    post('/api/pub/bankCardCheck?cardNumber='+num).then((result)=>{
      bankCards = this.props.form.getFieldsValue().bankCards
      const _bankCards = this.state.bankCards
      console.log('check:',bankCards.map((value,_index)=>{
        if(_index === index)
          value.bankName = result.data
        value.k = _bankCards[_index].k
        return value
      }),bankCards,_bankCards)
      this.setState({
        bankCardLoading:false,
        bankCards:bankCards.map((value,_index)=>{
          if(_index === index)
            value.bankName = result.data
          value.k = _bankCards[_index].k
          return value
        })
      })
    })
  }

  handleRemoveBank(index){
    const {bankCards} = this.state
    const formData = this.props.form.getFieldsValue().bankCards
    if(bankCards != null && bankCards.length > 1){
      bankCards.splice(index,1)
      formData.splice(index,1)
    }
    const newBankCards = formData.map((value,index)=>{
      value.k = bankCards[index].k
      return value
    })
    this.setState({
      bankCards:newBankCards,
    },this.props.onChange)
  }
  handleAddBank(){
    const {bankCards} = this.state
    bankCards.push({k:++banKeys})
    const formData = this.props.form.getFieldsValue().bankCards
    bankCards.map((value,index) => {
      value = {
        ...value,
        ...formData[index]
      }
    })
    this.setState({
      bankCards
    },this.props.onChange)
  }
  render(){
    const {form} = this.props
    const {bankCards,bankCardLoading,bankCardIndex} = this.state
    const {getFieldDecorator} = form
    console.log('render:',bankCards)
    return <Form>{bankCards.map((value,index) => (
        <Card key={'item'+index} title={'银行卡'+(index + 1)} bordered={false} style={{margin:'5px 0'}} extra={<Icon type="delete" className="close-icon-btn" onClick={this.handleRemoveBank.bind(this,index)} disabled={bankCards.length === 1}/>}>
            <FormItem
            label={'银行卡号'}
            {...itemLayout}
            hasFeedback
            >
              {getFieldDecorator('bankCards['+index+'].bankCardNumber', {
                initialValue:value.bankCardNumber,
                rules: [{
                  required: true, message: '请输入银行卡号'
                },{
                  validator:(rule, val, callback)=>{
                    if(!checkBankNum(val)){
                      callback('请输入正确的银行卡号')
                      this.insertBankCardName(index)
                    }else{
                      callback()
                      this.insertBankCardName(index)
                    }
                  }
                }],
              })(<Input/>)}
            </FormItem>
            <FormItem label={'开户行（自动生成）'} {...itemLayout}>
              {getFieldDecorator('bankCards['+index+'].bankName', {
                initialValue:value.bankName,
                rules: [{ required: true, message: '请输入开户行' }],
              })((bankCardLoading && bankCardIndex === index)?<Input suffix={<Icon type="loading"/>}/>:<Input />)}
            </FormItem>
            <FormItem key={value.k+'phoneNumber'} label={'银行绑定手机号'} {...itemLayout} hasFeedback>
              {getFieldDecorator('bankCards['+index+'].phoneNumber', {
                initialValue:value.phoneNumber,
                rules: [{
                  required: true, message: '请输入银行绑定手机号'
                },{
                  pattern:patterns.phoneNumber,
                  message:'请输入正确的手机号'
                }],
              })(<Input/>)}
            </FormItem>
            <FormItem label={'银行卡绑定人姓名'} {...itemLayout} hasFeedback>
              {getFieldDecorator('bankCards['+index+'].bindName', {
                initialValue:value.bindName,
                rules: [{ required: true, message: '请输入银行绑定人姓名' }],
              })(<Input />)}
            </FormItem>
            <FormItem label={'银行卡身份证号'} {...itemLayout} hasFeedback>
              {getFieldDecorator('bankCards['+index+'].bindCard', {
                initialValue:value.bindCard,
                rules: [{
                  required: true, message: '请输入银行绑定人身份证号'
                },{
                  pattern:patterns.idCard,message:'请输入正确的身份证号',
                }],
              })(<Input/>)}
            </FormItem>
        </Card>))}
        <div style={{margin:'15px 0 0',textAlign:'center'}}>
          <Button size="small" type="dashed" onClick={this.handleAddBank.bind(this)} style={{ width: '200px' ,lineHeight: '30px',height:30}}>
            <Icon type="plus" /> 添加银行卡
          </Button>
        </div>
      </Form>
  }
}

BankForm.propTypes = {
  bankCards:PropTypes.array,
  form:PropTypes.object,
  setForm:PropTypes.func,
  onChange:PropTypes.func.isRequired,
}

BankForm.defaultProps = {
  setForm:()=>{}
}

export default Form.create({
  onFieldsChange(props){
    props.onChange()
  }
})(BankForm)